<template>
    <div class="madp-data-detail">
        <backTitle
            v-if="isCstDetailShow"
            @goBack="goBack"
            title="
				数据详情
			"
        />
        <div v-show="!isCstDetailShow">
            <el-tabs v-model="dataType" type="card" @tab-click="changeDataType">
                <el-tab-pane label="集合数据" name="gather"></el-tab-pane>
                <el-tab-pane label="对比数据" name="compare"></el-tab-pane>
            </el-tabs>
            <div class="madp-statistics-data" v-show="dataType === 'gather'">
                <el-form class="madp-select-form" ref="collectParams" inline :model="collectParams">
                    <el-form-item label="渠道码:">
                        <div class="madp-code-group">
                            <el-popover placement="bottom-start" width="655" trigger="click" :visible-arrow="false" @show="showSelectOption = true" ref="codeGroupSelect">
                                <div class="madp-code-group-content" v-if="showSelectOption">
                                    <select-code
                                        selectType="collect"
                                        :defaultGroupAndCodeList="collectGroupAndCodeList"
                                        :defaultCodeIds="collectParams.channelId"
                                        :defaultGroupIds="collectParams.groupId"
                                        @closeSelectDialog="setShowSelectOptionVal"
                                        @confirmSelectCode="selectCollectCode"
                                    ></select-code>
                                </div>
                                <el-input v-model="collectParams.codeGroupName" placeholder slot="reference" readonly :title="collectParams.codeGroupName">
                                    <div class="madp-code-group-suffix" slot="suffix">
                                        <i class="el-icon-arrow-down"></i>
                                    </div>
                                </el-input>
                            </el-popover>
                        </div>
                    </el-form-item>
                </el-form>
                <statistics-card :cardInfo="cardInfo" :cardData="basicCstNumInfo" />
                <div class="madp-horizontal-divider"></div>
                <div class="madp-gap-wrap">
                    <div class="madp-gap-title">图表数据</div>
                    <div class="madp-statistics-tabs">
                        <div class="madp-statistics-tabs-left">
                            <el-button-group>
                                <el-button :type="collectParams.type === item.value ? 'primary' : ''" v-for="item in statisticDimensionTypes" :key="item.value" @click="selectDimensionType(item)">{{
                                    item.label
                                }}</el-button>
                            </el-button-group>
                            <el-popover placement="bottom-start" width="400" trigger="hover">
                                <div>
                                    <p>1、客户总数:扫码添加的客户总数，若客户重复添加将不会重复计数</p>
                                    <p>2、新增客户数:扫码添加的新增客户数，包含流失数据</p>
                                    <p>3、流失客户数:扫码添加后将成员删除的客户数</p>
                                </div>
                                <el-button type="text" slot="reference" style="margin-left: 20px">
                                    统计说明
                                    <i class="el-icon-question"></i>
                                </el-button>
                            </el-popover>
                        </div>
                    </div>
                    <div class="madp-date-picker-wrap madp-statistics-tabs">
                        <div class="madp-statistics-tabs-left">
                            <el-form :inline="true" class="madp-chart-form">
                                <el-form-item>
                                    <el-select class="madp-date-select" v-model="gatherDateType" placeholder="请选择">
                                        <el-option v-for="item in dateTypes" :key="item.type" :label="item.label" :value="item.type"></el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="自定义:">
                                    <el-date-picker
                                        v-model="collectParams.scopeTime"
                                        type="daterange"
                                        range-separator="至"
                                        start-placeholder="开始日期"
                                        end-placeholder="结束日期"
                                        :picker-options="{
                                            disabledDate(time) {
                                                return time.getTime() > Date.now();
                                            }
                                        }"
                                        format="yyyy-MM-dd"
                                        value-format="yyyy-MM-dd"
                                        @change="resetDateType"
                                    ></el-date-picker>
                                </el-form-item>
                                <el-form-item label="请选择员工:">
                                    <el-select v-model="collectParams.employeeId" placeholder="请选择员工" filterable @change="() => queryDataByParamsChange('collectParams')">
                                        <el-option v-for="item in employeeList" :key="item.employeeId" :label="item.name" :value="item.employeeId"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-form>
                        </div>
                        <el-button plain @click="onCollectReset(1)">重置</el-button>
                    </div>
                    <!-- 折线图 -->
                    <div id="gatherLineChart" style="width: 100%; height: 400px; margin: 30px auto"></div>
                </div>
                <div class="madp-horizontal-divider"></div>
                <div class="madp-gap-wrap">
                    <div class="madp-gap-title">表格数据</div>
                    <div class="madp-statistics-tabs">
                        <el-button-group>
                            <el-button :type="tableType === 'date' ? 'primary' : ''" @click="queryCollectTableData('date')">按日期查看</el-button>
                            <el-button :type="tableType === 'staff' ? 'primary' : ''" @click="queryCollectTableData('staff')">按员工查看</el-button>
                        </el-button-group>
                        <download-btn title="导出Excel" @click="downloadExcel" />
                    </div>
                    <div class="madp-statistics-table" v-show="tableType === 'date'">
                        <el-table
                            :data="collectTableDataByDate"
                            :header-cell-style="{
                                background: 'rgb(255, 191, 191)',
                                color: 'rgb(44,44,44)'
                            }"
                            stripe
                        >
                            <el-table-column prop="createTime" label="日期" width="150" align="center"></el-table-column>
                            <el-table-column prop="allAddContact" label="客户总数" width="200" align="center"></el-table-column>
                            <el-table-column prop="newAddContact" label="新增人数" align="center"></el-table-column>
                            <el-table-column prop="newLossContact" label="流失人数" align="center"></el-table-column>
                            <el-table-column label="操作" align="center">
                                <template slot-scope="scope">
                                    <el-button type="text" @click="showDetail(scope.row)">查看详情</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                    <div class="madp-bottom-pagination" v-show="tableType === 'date'">
                        <el-pagination
                            background
                            :current-page="collectDatePage.current"
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :page-sizes="[10, 20, 30, 50, 100]"
                            :page-size="collectDatePage.size"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="collectDatePage.total"
                            style="float: right"
                        ></el-pagination>
                    </div>
                    <div class="madp-statistics-table" v-show="tableType !== 'date'">
                        <el-table
                            :data="collectTableDataByStaff"
                            :header-cell-style="{
                                background: 'rgb(255, 191, 191)',
                                color: 'rgb(44,44,44)'
                            }"
                            stripe
                        >
                            <el-table-column prop="name" label="员工名称" width="150" align="center">
                                <template slot-scope="scope">
                                    <div class="madp-table-user">
                                        <img :src="scope.row.avatar" alt />
                                        <span>{{ scope.row.name || '--' }}</span>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="allAddContact" label="客户总数" width="200" align="center"></el-table-column>
                            <el-table-column prop="newAddContact" label="新增人数" align="center"></el-table-column>
                            <el-table-column prop="allLossContact" label="流失人数" align="center"></el-table-column>
                            <el-table-column label="操作" align="center">
                                <template slot-scope="scope">
                                    <el-button type="text" @click="showDetail(scope.row)">查看详情</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                    <div class="madp-bottom-pagination" v-show="tableType !== 'date'">
                        <el-pagination
                            background
                            :current-page="collectStaffPage.current"
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :page-sizes="[10, 20, 30, 50, 100]"
                            :page-size="collectStaffPage.size"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="collectStaffPage.total"
                            style="float: right"
                        ></el-pagination>
                    </div>
                </div>
            </div>
            <div class="madp-statistics-data" v-show="dataType === 'compare'">
                <div class="madp-data-title">对比数据</div>
                <div class="madp-select-code-wrap">
                    <div class="madp-select-code">
                        <el-button icon="el-icon-plus" type="primary" @click="showSelectDialog">添加渠道码</el-button>
                        <span class="madp-code-tip">最多同时对比五个渠道码（组）</span>
                    </div>
                    <download-btn title="导出Excel" @click="downloadCompareExcel" />
                </div>
                <div class="madp-gap-wrap">
                    <el-table
                        class="madp-compare-table"
                        :data="compareTableData"
                        :header-cell-style="{
                            background: 'rgb(255, 191, 191)',
                            color: 'rgb(44,44,44)'
                        }"
                        stripe
                    >
                        <el-table-column width="50" align="center">
                            <template slot-scope="scope">
                                <i
                                    class="madp-color-point"
                                    :style="{
                                        background: colorList[scope.$index]
                                    }"
                                ></i>
                            </template>
                        </el-table-column>
                        <el-table-column prop="codeName" label="渠道码（组）名称" width="200" align="center">
                            <template slot-scope="scope">
                                <img class="madp-code-icon" src="/img/group-icon.png" v-if="scope.row.type === 1" />
                                <img class="madp-code-icon" src="/img/code-icon.png" v-else />
                                {{ scope.row.name }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="newAddContact" label="今日添加客户数" align="center"></el-table-column>
                        <el-table-column prop="newLossContact" label="今日流失客户数" align="center"></el-table-column>
                        <el-table-column prop="allAddContact" label="总添加客户人数" align="center"></el-table-column>
                        <el-table-column prop="allLossContact" label="总流失客户人数" align="center"></el-table-column>
                        <el-table-column label="操作" align="center">
                            <template slot-scope="scope">
                                <el-button type="text" @click="delSelectedCodeOrGroup(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                        <div slot="empty" class="madp-table-nodata">
                            <div>
                                <img src="/img/nodata.png" alt />
                            </div>
                            <div>
                                <span>请先添加渠道码</span>
                                <el-button class="madp-table-nodata-btn" @click="showSelectDialog" type="text">立即添加</el-button>
                            </div>
                        </div>
                    </el-table>
                </div>
                <div class="madp-horizontal-divider"></div>
                <div class="madp-gap-wrap">
                    <div class="madp-gap-title">图表数据</div>
                    <div class="madp-statistics-tabs">
                        <div class="madp-statistics-tabs-left">
                            <el-button-group>
                                <el-button :type="compareParams.type === item.value ? 'primary' : ''" v-for="item in statisticDimensionTypes" :key="item.value" @click="selectDimensionType(item)">{{
                                    item.label
                                }}</el-button>
                            </el-button-group>
                            <el-popover placement="bottom-start" width="400" trigger="hover">
                                <div>
                                    <p>1、客户总数:扫码添加的客户总数，若客户重复添加将不会重复计数</p>
                                    <p>2、新增客户数:扫码添加的新增客户数，包含流失数据</p>
                                    <p>3、流失客户数:扫码添加后将成员删除的客户数</p>
                                </div>
                                <el-button type="text" slot="reference" style="margin-left: 20px">
                                    统计说明
                                    <i class="el-icon-question"></i>
                                </el-button>
                            </el-popover>
                        </div>
                    </div>
                    <div class="madp-date-picker-wrap madp-statistics-tabs">
                        <div class="madp-statistics-tabs-left">
                            <el-form :inline="true" class="madp-chart-form">
                                <el-form-item>
                                    <el-select class="madp-date-select" v-model="compareDateType" placeholder="请选择">
                                        <el-option v-for="item in dateTypes" :key="item.type" :label="item.label" :value="item.type"></el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="自定义:">
                                    <el-date-picker
                                        v-model="compareParams.scopeTime"
                                        type="daterange"
                                        range-separator="至"
                                        start-placeholder="开始日期"
                                        end-placeholder="结束日期"
                                        :picker-options="{
                                            disabledDate(time) {
                                                return time.getTime() > Date.now();
                                            }
                                        }"
                                        format="yyyy-MM-dd"
                                        value-format="yyyy-MM-dd"
                                        @change="resetDateType"
                                    ></el-date-picker>
                                </el-form-item>
                                <el-form-item label="请选择员工:">
                                    <el-select v-model="compareParams.employeeId" placeholder="请选择员工" filterable @change="() => queryDataByParamsChange('compareParams')">
                                        <el-option v-for="item in employeeList" :key="item.employeeId" :label="item.name" :value="item.employeeId"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-form>
                        </div>
                        <el-button plain @click="onCollectReset(2)">重置</el-button>
                    </div>
                    <!-- 折线图 -->
                    <div id="compareLineChart" style="width: 100%; height: 400px; margin: 30px auto"></div>
                </div>
            </div>
        </div>

        <div v-if="isCstDetailShow" class="madp-pt">
            <customer-detail :detailMsg="detailMsg" :backShow="false" :isComponent="true"></customer-detail>
        </div>

        <!-- 选择活码弹框 -->
        <el-dialog class="madp-select-dialog" title="添加渠道码" :close-on-click-modal="false" :visible.sync="showSelectCode" v-if="showSelectCode" center>
            <div class="madp-select-content-wrap">
                <div class="madp-black-tip-wrap">
                    <i class="el-icon-message-solid madp-message-solid"></i>
                    <span>选最多同时对比五个渠道码（组）</span>
                </div>
                <select-code
                    selectType="compare"
                    :defaultGroupAndCodeList="compareGroupAndCodeList"
                    :defaultCodeIds="compareParams.channelId"
                    :defaultGroupIds="compareParams.groupId"
                    @closeSelectDialog="closeSelectDialog"
                    @confirmSelectCode="selectCompareCode"
                ></select-code>
            </div>
        </el-dialog>
        <div v-if="!isCstDetailShow">
            <el-dialog title="查看详情" :close-on-click-modal="false" :visible.sync="detailVisible" @close="onCloseDetail" width="1000px">
                <div class="madp-detail">
                    <div class="madp-detail-btn">
                        <el-button-group>
                            <el-button
                                :type="dimensionDialogType === item.value ? 'primary' : ''"
                                v-for="item in statisticDimensionTypes"
                                :key="item.value"
                                @click="
                                    dimensionDialogType = item.value;
                                    showDetail(selectedRow, item.value);
                                "
                                >{{ item.label }}</el-button
                            >
                        </el-button-group>
                        <span class="madp-detail-btn-desc">管理权限范围不同，展示的客户详情数据也不同哦～</span>
                    </div>
                    <div class="madp-detail-basic">
                        <div class="madp-detail-basic-info">
                            <div class="madp-detail-basic-info-num">共{{ collectDetailPage.total }}个客户</div>
                            <div class="madp-detail-basic-info-time" v-if="tableType === 'date'">{{ selectedRow.createTime }}</div>
                            <div v-else>{{ selectedRow.name }}</div>
                        </div>
                        <download-btn title="导出Excel" @click="downloadDetailExcel" />
                    </div>
                    <div class="madp-common-mt">
                        <el-table
                            :header-cell-style="{
                                background: 'rgb(255, 191, 191)',
                                color: 'rgb(44,44,44)'
                            }"
                            stripe
                            :data="collectDetailData"
                        >
                            <el-table-column prop="contactName" label="全部客户" align="center"></el-table-column>
                            <el-table-column prop="employeeName" label="所属客服" align="center"></el-table-column>
                            <el-table-column prop="tagsList" label="标签" align="center">
                                <template slot-scope="scope">
                                    {{ scope.row.tagsList && scope.row.tagsList.length > 0 ? scope.row.tagsList.toString() : '--' }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="statusMsg" label="客户状态" align="center"></el-table-column>
                            <el-table-column prop="createTime" label="添加时间" align="center">
                                <template slot-scope="scope">
                                    <div v-if="scope.row.createTime">
                                        <div>
                                            {{ scope.row.createTime.slice(0, 10) }}
                                        </div>
                                        <div>{{ scope.row.createTime.slice(11) }}</div>
                                    </div>
                                    <div v-else>--</div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="lastTime" label="上次对话时间" align="center">
                                <template slot-scope="scope">
                                    <div v-if="scope.row.lastTime">
                                        <div>
                                            {{ scope.row.lastTime.slice(0, 10) }}
                                        </div>
                                        <div>{{ scope.row.lastTime.slice(11) }}</div>
                                    </div>
                                    <div v-else>--</div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="channel" label="添加渠道" align="center">
                                <template slot-scope="scope">
                                    <div>{{ scope.row.channel || '--' }}</div>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                    <div class="madp-bottom-pagination">
                        <el-pagination
                            background
                            :current-page="collectDetailPage.current"
                            @size-change="handleDetailSizeChange"
                            @current-change="handleDetailCurrentChange"
                            :page-sizes="[10, 20, 30, 50, 100]"
                            :page-size="collectDetailPage.size"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="collectDetailPage.total"
                            style="float: right"
                        ></el-pagination>
                    </div>
                </div>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="onCloseDetail" type="primary">确定</el-button>
                </div>
            </el-dialog>
        </div>
    </div>
</template>
<script>
import SelectCode from './components/select-code.vue';
import backTitle from '@/components/back-title/';
import customerDetail from '@/views/customer/customer-list/detail';
import { queryCodeGroupList, queryChannelCode } from '@/api/customers-of-drainage/customers-of-drainage';
import {
    getChannelBasicInfo,
    getChannelEchartsInfo,
    getChannelInfoByDate,
    downloadChannelInfoByDate,
    getChannelDetailByDate,
    downloadChannelDetailByDate,
    getChannelInfoByStaff,
    downloadChannelInfoByStaff,
    getChannelDetailByStaff,
    downloadChannelDetailByStaff,
    compareCodeOrGroupTable,
    downloadcompareCodeOrGroup,
    compareCodeOrGroupEchart
} from '@/api/customers-of-drainage/statistics';
import { getDepartmentList } from '@/api/common-interface/department';
import { dateFormat } from '@/util/date';
import { downloadFile } from '@/util/util';
import DownloadBtn from '@/components/download-btn/';
import StatisticsCard from '@/components/statistics-card/';
export default {
    components: {
        SelectCode,
        backTitle,
        customerDetail,
        DownloadBtn,
        StatisticsCard
    },
    props: ['selectedGroup'],
    data() {
        return {
            dataType: 'gather',
            collectParams: {
                codeGroupName: '',
                channelId: [],
                groupId: [],
                type: 1, //维度 客户总数、新增客户数、流失客户数
                employeeId: '',
                scopeTime: []
            },
            collectSendParams: {}, // 已处理的请求参数
            collectChartData: [],
            collectTableDataByDate: [],
            collectTableDataByStaff: [],
            collectDatePage: {
                current: 1,
                size: 10,
                total: 0
            },
            collectStaffPage: {
                current: 1,
                size: 10,
                total: 0
            },
            collectDetailData: [],
            collectDetailPage: {
                current: 1,
                size: 10,
                total: 0
            },
            compareParams: {
                codeGroupName: '',
                channelId: [],
                groupId: [],
                type: 1,
                scopeTime: []
            },
            compareChartData: [],
            employeeList: [], // 待选择成员
            basicCstNumInfo: {},
            gatherDimensionTypeName: '客户总数',
            compareDimensionType: 0, //维度 客户总数、新增客户数、流失客户数
            compareDimensionTypeName: '客户总数',
            statisticDimensionTypes: [
                {
                    label: '客户总数',
                    value: 1
                },
                {
                    label: '新增客户数',
                    value: 2
                },
                {
                    label: '流失客户数',
                    value: 3
                }
            ],
            // 快捷日期
            dateTypes: [
                {
                    type: 0,
                    label: '今日'
                },
                {
                    type: 1,
                    label: '近一周'
                },
                {
                    type: 2,
                    label: '近一个月'
                }
            ],
            //集合数据日期选择
            gatherDateType: null,
            compareDateType: null,
            tableType: 'date',
            //折线图数据
            lineChartOption: {},
            chartData: [],
            // 集合数据
            showSelectOption: false,
            collectGroupAndCodeList: [],

            // 对比数据相关联data
            compareTableData: [],
            colorList: ['#01A3FE', '#00D06A', '#FED000', '#FE5079', '#A25AEA'],
            // 添加渠道码弹框相关
            showSelectCode: false,
            compareGroupAndCodeList: [],
            detailVisible: false,
            selectedRow: {},
            dimensionDialogType: 1,
            detailMsg: {},
            isCstDetailShow: false,
            firstGroupId: 0,
            cardInfo: [
                {
                    label: '今日添加客户数(人)',
                    key: 'newAddContact',
                    color: '#FFD700'
                },
                {
                    label: '今日流失客户数(人)',
                    key: 'newLossContact',
                    color: '#FF8C00'
                },
                {
                    label: '总添加客户数(人)',
                    key: 'allAddContact',
                    color: '#90EE90'
                },
                {
                    label: '总流失客户数(人)',
                    key: 'allLossContact',
                    color: '#00CED1'
                }
            ]
        };
    },
    watch: {
        gatherDateType(newVal, oldVal) {
            if (newVal === null) {
                return;
            }
            let nowDate = new Date();
            let startDate = new Date();
            if (newVal === 0) {
                this.collectParams.scopeTime = [startDate, nowDate];
            } else if (newVal === 1) {
                startDate.setTime(nowDate.getTime() - 3600 * 1000 * 24 * 6);
                this.collectParams.scopeTime = [startDate, nowDate];
            } else {
                startDate.setTime(nowDate.getTime() - 3600 * 1000 * 24 * 29);
                this.collectParams.scopeTime = [startDate, nowDate];
            }
            if (this.collectGroupAndCodeList && this.collectGroupAndCodeList.length > 0) {
                this.queryDataByParamsChange('collectParams');
            }
        },
        compareDateType(newVal, oldVal) {
            if (newVal === null) {
                return;
            }
            let nowDate = new Date();
            let startDate = new Date();
            if (newVal === 0) {
                this.compareParams.scopeTime = [startDate, nowDate];
            } else if (newVal === 1) {
                startDate.setTime(nowDate.getTime() - 3600 * 1000 * 24 * 6);
                this.compareParams.scopeTime = [startDate, nowDate];
            } else {
                startDate.setTime(nowDate.getTime() - 3600 * 1000 * 24 * 29);
                this.compareParams.scopeTime = [startDate, nowDate];
            }
            if (this.compareGroupAndCodeList && this.compareGroupAndCodeList.length > 0) {
                this.queryDataByParamsChange('compareParams');
            }
        }
    },
    created() {
        this.gatherDateType = 1;
        this.compareDateType = 1;
        this.fetchEmployeeList();
    },
    mounted() {
        this.firstGroupId = this.selectedGroup;
        this.$nextTick(() => {
            this.getFirstChannelId();
        });
    },
    methods: {
        goBack() {
            this.detailMsg = {};
            this.isCstDetailShow = false;
            this.$emit('changeTabShow', true);
        },
        // 成员数据列表
        fetchEmployeeList() {
            getDepartmentList().then((res) => {
                if (res.data && res.data.code === 0) {
                    let data = res.data.data;
                    let { employee } = data;
                    this.employeeList = [{ employeeId: '', name: '请选择' }].concat(employee);
                }
            });
        },
        // 获取第一个分组下的第一个活码
        getFirstChannelId() {
            queryChannelCode({
                groupId: this.firstGroupId ? this.firstGroupId : undefined
            }).then((res) => {
                if (res.data.code === 0 && res.data.data) {
                    const firtsChannel = res.data.data.records || [];
                    const firstChannelId = firtsChannel[0] ? firtsChannel[0].id : undefined;
                    const firstChannelName = firtsChannel[0] ? firtsChannel[0].name : undefined;
                    this.collectParams.channelId = [firstChannelId];
                    this.collectParams.codeGroupName = firstChannelName;
                    this.collectGroupAndCodeList = JSON.parse(
                        JSON.stringify([
                            {
                                ...firtsChannel[0],
                                channelId: firtsChannel[0].id,
                                id: firtsChannel[0].id + 'code',
                                name: firtsChannel[0].name,
                                type: 2,
                                isChecked: true
                            }
                        ])
                    );
                    // 拿到第一个分组第一条活码后，查询聚合数据
                    this.getBasicInfo();
                    this.queryDataByParamsChange('collectParams');
                }
            });
        },
        // 聚合数据活码选择
        selectCollectCode(obj) {
            this.collectParams.codeGroupName = obj.codeGroupName;
            this.collectParams.groupId = obj.selectGroupIds;
            this.collectParams.channelId = obj.selectCodeIds;
            this.collectGroupAndCodeList = obj.selectGroupAndCodeList;
            this.$refs.codeGroupSelect.doClose();
            this.showSelectOption = false;
            this.getBasicInfo();
            this.queryDataByParamsChange('collectParams');
        },
        // 获取客户统计基本信息
        getBasicInfo() {
            const params = {
                channelId: this.collectParams.channelId,
                groupId: this.collectParams.groupId
            };
            getChannelBasicInfo(params).then((res) => {
                if (res.data.code === 0) {
                    this.basicCstNumInfo = res.data.data || {};
                }
            });
        },
        // 切换对比数据、集合数据
        changeDataType(tab, event) {
            let lineChartId = '';
            if (this.dataType === 'gather') {
                lineChartId = 'gatherLineChart';
            } else {
                lineChartId = 'compareLineChart';
            }
            this.echartsFn(lineChartId);
        },
        // 集合数据相关的
        setShowSelectOptionVal() {
            this.$refs.codeGroupSelect.doClose();
            this.showSelectOption = false;
        },
        // 聚合数据查询参数变更，重新请求页面数据
        queryDataByParamsChange(type) {
            const params = {
                channelId: this[type].channelId,
                groupId: this[type].groupId,
                type: this[type].type,
                employeeId: this[type].employeeId,
                startTime: typeof this[type].scopeTime[0] !== 'string' ? dateFormat(this[type].scopeTime[0]).slice(0, 10) : this[type].scopeTime[0],
                endTime: typeof this[type].scopeTime[1] !== 'string' ? dateFormat(this[type].scopeTime[1]).slice(0, 10) : this[type].scopeTime[1]
            };
            this.collectDatePage = {
                current: 1,
                size: 10,
                total: 0
            };
            this.collectStaffPage = {
                current: 1,
                size: 10,
                total: 0
            };
            if (type === 'collectParams') {
                this.collectSendParams = params;
                getChannelEchartsInfo(params).then((res) => {
                    if (res.data.code === 0) {
                        this.collectChartData = res.data.data || [];
                        this.echartsFn('gatherLineChart');
                    }
                });
                this.queryCollectTableData();
            } else {
                compareCodeOrGroupEchart(params).then((res) => {
                    if (res.data.code === 0) {
                        this.compareChartData = res.data.data || [];
                        this.echartsFn('compareLineChart');
                    }
                });
            }
        },
        //
        handleSizeChange(size) {
            if (this.tableType === 'date') {
                this.collectDatePage.size = size;
            } else {
                this.collectStaffPage.size = size;
            }
            this.queryCollectTableData();
        },
        //
        handleCurrentChange(current) {
            if (this.tableType === 'date') {
                this.collectDatePage.current = current;
            } else {
                this.collectStaffPage.current = current;
            }
            this.queryCollectTableData();
        },
        // 查询聚合数据表格数据
        queryCollectTableData(type) {
            if (type) {
                this.tableType = type;
            }
            const params = {
                ...this.collectSendParams
            };
            if (this.tableType === 'staff') {
                params.current = type ? 1 : this.collectStaffPage.current;
                params.size = type ? 10 : this.collectStaffPage.size;
                getChannelInfoByStaff(params).then((res) => {
                    if (res.data.code === 0) {
                        this.collectTableDataByStaff = res.data.data.records || [];
                        this.collectStaffPage.total = res.data.data.total;
                    }
                });
            } else {
                params.current = type ? 1 : this.collectDatePage.current;
                params.size = type ? 10 : this.collectDatePage.size;
                getChannelInfoByDate(params).then((res) => {
                    if (res.data.code === 0) {
                        this.collectTableDataByDate = res.data.data.records || [];
                        this.collectDatePage.total = res.data.data.total;
                    }
                });
            }
        },
        // 切换图表数据参数
        selectDimensionType(item) {
            let lineChartId = '';
            if (this.dataType === 'gather') {
                this.collectParams.type = item.value;
                this.gatherDimensionTypeName = item.label;
                this.queryDataByParamsChange('collectParams');
            } else {
                lineChartId = 'compareLineChart';
                this.compareParams.type = item.value;
                this.compareDimensionTypeName = item.label;
                // 调查询接口
                this.queryDataByParamsChange('compareParams');
            }
        },
        // 日期选择后重置dateType值为null
        resetDateType(val) {
            if (this.dataType === 'gather') {
                this.gatherDateType = null;
                this.queryDataByParamsChange('collectParams');
            } else {
                this.compareDateType = null;
                this.queryDataByParamsChange('compareParams');
            }
        },
        // 聚合数据重置按钮
        onCollectReset(type) {
            if (type === 1) {
                this.gatherDateType = 1;
                this.collectParams.type = 1;
                this.collectParams.employeeId = '';
                this.queryDataByParamsChange('collectParams');
            } else {
                if (!this.compareGroupAndCodeList || this.compareGroupAndCodeList.length === 0) {
                    return;
                }
                this.compareDateType = 1;
                this.collectParams.type = 1;
                this.compareParams.employeeId = '';
                this.queryDataByParamsChange('compareParams');
            }
        },
        // 折线图配置
        echartsFn(eleId) {
            let lineChartOption = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        // 坐标轴指示器，坐标轴触发有效
                        type: 'line' // 默认为直线，可选为:'line' | 'shadow'
                    },
                    formatter: '{b}<br>客户总数: {c}'
                },
                xAxis: {
                    type: 'category',
                    data: []
                },
                yAxis: {
                    name: '人数',
                    type: 'value'
                },
                series: [
                    {
                        name: '客户总数',
                        type: 'line',
                        data: [],
                        lineStyle: {
                            color: '#ED5555'
                        },
                        itemStyle: {
                            color: '#ED5555'
                        }
                    }
                ]
            };
            let xAxisData = [];
            let seriesData = [];
            if (eleId === 'gatherLineChart') {
                this.collectChartData.forEach((item, index) => {
                    xAxisData.push(item.createTime);
                    seriesData.push(item.counts);
                });
                if (lineChartOption.series[0]) {
                    lineChartOption.series[0].data = seriesData;
                } else {
                    lineChartOption.series = [
                        {
                            name: this.gatherDimensionTypeName,
                            type: 'line',
                            data: seriesData,
                            lineStyle: {
                                color: '#ED5555'
                            },
                            itemStyle: {
                                color: '#ED5555'
                            }
                        }
                    ];
                }
                lineChartOption.tooltip.formatter = `{b}<br>${this.dataType === 'gather' ? this.gatherDimensionTypeName : this.compareDimensionTypeName}: {c}`;
            } else {
                const legend = [];
                this.compareChartData.forEach((item, index) => {
                    item.dataList.forEach((it) => {
                        if (!xAxisData.includes(it.date)) {
                            xAxisData.push(it.date);
                        }
                    });
                    seriesData.push({
                        name: item.name,
                        type: 'line',
                        data: item.dataList.map((it) => it.count)
                    });
                    legend.push(item.name);
                });
                lineChartOption.series = JSON.parse(JSON.stringify(seriesData));
                lineChartOption.legend = {
                    data: legend
                };
                lineChartOption.tooltip.formatter = (params) => {
                    let message = '';
                    let isFirst = true;
                    params.forEach((item) => {
                        if (isFirst) {
                            message += item.name + '<br>' + this.compareDimensionTypeName;
                            isFirst = false;
                        }
                        message +=
                            '<br>' +
                            `<span
								style="
									background: ${item.color};
									display: inline-block;
									width: 12px;
									height: 12px;
									border-radius: 50%;
									margin: 5px 5px 0 0;
								"
							>
							</span>` +
                            item.seriesName +
                            ':' +
                            item.value;
                    });
                    return message;
                };
            }
            lineChartOption.xAxis.data = xAxisData;
            let echarts = require('echarts');

            // 绘制图表
            this.$nextTick(() => {
                // 基于准备好的dom，初始化echarts实例
                let myChart = echarts.init(document.getElementById(eleId));
                myChart.setOption(lineChartOption, true);
            });
        },
        //
        handleDetailSizeChange(size) {
            this.collectDetailPage.size = size;
            this.showDetail(this.selectedRow, this.dimensionDialogType, true);
        },
        //
        handleDetailCurrentChange(current) {
            this.collectDetailPage.current = current;
            this.showDetail(this.selectedRow, this.dimensionDialogType, true);
        },
        // 聚合数据表格查看详情
        showDetail(row, type, isPageChange) {
            // 获取详情数据
            this.selectedRow = row;
            const params = {
                ...this.collectParams,
                type: type || 1,
                current: isPageChange ? this.collectDetailPage.current : 1,
                size: isPageChange ? this.collectDetailPage.size : 10
            };
            let requestUrl = '';
            if (this.tableType === 'date') {
                requestUrl = getChannelDetailByDate;
                params.startTime = row.createTime;
                params.endTime = row.createTime;
            } else {
                requestUrl = getChannelDetailByStaff;
                params.employeeId = row.employeeId;
            }
            requestUrl(params).then((res) => {
                if (res.data.code === 0) {
                    this.detailVisible = true;
                    this.collectDetailData = res.data.data.records || [];
                    this.collectDetailPage.total = res.data.data.total;
                }
            });
        },
        // 查看客户详情
        showCstDetail(row) {
            this.detailMsg = row;
            this.$emit('changeTabShow', false);
            this.isCstDetailShow = true;
        },
        // 关闭详情弹框
        onCloseDetail() {
            this.detailVisible = false;
            this.collectDetailPage = {
                current: 1,
                size: 10,
                total: 0
            };
            this.dimensionDialogType = 1;
            this.selectedRow = {};
        },

        // 添加渠道码
        showSelectDialog() {
            this.showSelectCode = true;
        },
        // 关闭活码选择弹框
        closeSelectDialog() {
            this.showSelectCode = false;
        },
        // 对比数据选择渠道活码
        selectCompareCode(obj) {
            this.compareParams.codeGroupName = obj.codeGroupName;
            this.compareParams.channelId = obj.selectCodeIds;
            this.compareParams.groupId = obj.selectGroupIds;
            this.compareGroupAndCodeList = obj.selectGroupAndCodeList;
            this.closeSelectDialog();
            this.getCompareTableData();
            this.queryDataByParamsChange('compareParams');
        },
        // 导出聚合数据
        downloadExcel() {
            const params = {
                ...this.collectSendParams,
                type: undefined
            };
            let requestUrl = downloadChannelInfoByDate;
            let mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
            if (this.tableType === 'staff') {
                delete params.employeeId;
                requestUrl = downloadChannelInfoByStaff;
                mimeType = 'application/vnd.ms-excel';
            }
            requestUrl(params).then((res) => {
                const fileName = params.startTime + '至' + params.endTime + `${this.tableType === 'date' ? '按日期' : '按客服'}` + '添加客户数据统计';
                downloadFile(res, fileName);
            });
        },
        // 导出聚合数据客户详情
        downloadDetailExcel() {
            const params = {
                ...this.collectSendParams,
                type: this.dimensionDialogType
            };
            let requestUrl = '';
            let fileNameTime = params.startTime + '至' + params.endTime;
            if (this.tableType === 'date') {
                requestUrl = downloadChannelDetailByDate;
                params.startTime = this.selectedRow.createTime;
                params.endTime = this.selectedRow.createTime;
                fileNameTime = params.startTime;
            } else {
                requestUrl = downloadChannelDetailByStaff;
                params.employeeId = this.selectedRow.employeeId;
            }
            requestUrl(params).then((res) => {
                const fileName = fileNameTime + '日添加的客户详情';
                downloadFile(res, fileName);
            });
        },
        // 获取对比数据基本信息
        getCompareTableData() {
            const params = {
                channelId: this.compareParams.channelId,
                groupId: this.compareParams.groupId
            };
            compareCodeOrGroupTable(params).then((res) => {
                if (res.data.code === 0) {
                    this.compareTableData = res.data.data || 0;
                }
            });
        },
        // 取消某条数据对比信息
        delSelectedCodeOrGroup(row) {
            if (row.type === 1) {
                this.compareParams.groupId = this.compareParams.groupId.filter((item) => item !== row.id);
                this.compareGroupAndCodeList = this.compareGroupAndCodeList.filter((item) => item.groupId !== row.id);
            } else {
                this.compareParams.channelId = this.compareParams.channelId.filter((item) => item !== row.id);
                this.compareGroupAndCodeList = this.compareGroupAndCodeList.filter((item) => item.channelId !== row.id);
            }
            this.getCompareTableData();
            this.queryDataByParamsChange('compareParams');
        },
        // 导出对比数据
        downloadCompareExcel() {
            const params = {
                channelId: this.compareParams.channelId,
                groupId: this.compareParams.groupId
            };
            downloadcompareCodeOrGroup(params).then((res) => {
                downloadFile(res, '客户统计对比数据');
            });
        }
    }
};
</script>
<style lang="scss" scoped>
/deep/ .el-button--primary.is-plain {
    background-color: #fff;
    border-color: #ed5555;
}
/deep/ .madp-compare-table.el-table {
    border: 1px solid #ebeef5;
}
/deep/ .madp-compare-table.el-table .cell {
    display: flex;
    align-items: center;
}
.madp-code-icon {
    width: 18px;
    height: auto;
    margin-right: 5px;
}
.madp-compare-table.el-table--border::after,
.madp-compare-table.el-table::before {
    content: '';
    position: absolute;
    background-color: #fff;
    z-index: 1;
}
.madp-color-point {
    width: 12px;
    height: 12px;
    border-radius: 50%;
    display: inline-block;
}
.madp-code-group {
    /deep/ .el-input {
        input {
            cursor: pointer;
        }
    }
    .madp-code-group-suffix {
        padding-right: 10px;
        cursor: pointer;
    }
}
.madp-statistics-data {
    margin-top: 20px;
}
.madp-select-form .el-form-item {
    margin-bottom: 0;
}
.madp-data-title {
    font-size: 16px;
    font-weight: bold;
    color: #333;
}
.madp-select-code-wrap {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 10px;
    .madp-code-tip {
        color: #a8a8a8;
        margin-left: 10px;
    }
}
.madp-top-statistics-boxs {
    display: flex;
    align-items: center;
    margin-top: 20px;
}
.madp-top-statistics-box {
    width: 420px;
    height: 118px;
    background: #fbfdff;
    border: 1px solid #cfe8ff;
    display: flex;
    -webkit-box-align: center;
    align-items: center;
    position: relative;
    margin-right: 20px;
    .madp-divider {
        width: 1px;
        height: 50px;
        background-color: #f2f2f2;
    }
    .madp-statistics-item {
        width: 48%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        .madp-statistics-item-number {
            font-size: 20px;
            font-weight: bold;
        }
    }
}

.madp-horizontal-divider {
    width: 100%;
    height: 4px;
    margin: 20px 0;
    background-color: #f0f2f5;
}
.madp-gap-wrap {
    margin-top: 10px;
    .madp-gap-title {
        font-weight: bold;
        color: #333;
        line-height: 24px;
        font-size: 16px;
    }
    .madp-statistics-tabs {
        margin-top: 20px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .madp-chart-form .el-form-item {
            margin-right: 20px;
            margin-bottom: 0;
        }
        .madp-date-select {
            width: 120px;
        }
        .el-date-editor--daterange.el-input__inner {
            width: 300px;
        }
        /deep/ .el-date-editor .el-range-separator {
            width: 25px !important;
        }
    }
    .madp-statistics-table {
        margin-top: 20px;
    }
}

/deep/ .madp-select-dialog .el-dialog {
    width: 655px;
    border-radius: 4px;
    .el-dialog__title {
        font-size: 16px;
        font-weight: bold;
    }
    .el-dialog__body {
        padding: 10px 25px 20px;
    }
}
.madp-select-content-wrap {
    .madp-black-tip-wrap {
        width: 100%;
        font-size: 14px;
        color: #333;
        padding: 8px 10px;
        border-radius: 2px;
        background: #f0f8ff;
        .madp-message-solid {
            color: #1890ff;
            margin-right: 5px;
        }
    }
}
.madp-detail {
    &-btn {
        &-desc {
            margin-left: 10px;
            color: #999;
        }
    }
    &-basic {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 10px;
        &-info {
            display: flex;
            align-items: center;
            &-num {
                font-size: 14px;
                font-weight: 600;
                margin-right: 10px;
            }
            &-time {
                padding-left: 10px;
                line-height: 14px;
                font-size: 12px;
                border-left: 1px solid #e6e6e6;
                color: #999;
            }
        }
    }
}
.madp-download-btn {
    .el-button {
        border-color: #1890ff;
        color: #1890ff;
    }
}
.madp-pt {
    padding-top: 50px;
}
.madp-bottom-pagination {
    margin-top: 16px;
}
.madp-common-mt {
    margin-top: 20px;
}
.madp-table-nodata {
    padding: 20px;
    line-height: 32px;
    &-btn {
        margin-left: 10px;
    }
}
.madp-table-user {
    display: flex;
    align-items: center;
    justify-content: center;
    img {
        width: 32px;
        height: 32px;
    }
    span {
        margin-left: 5px;
    }
}
</style>
